package at.jku.ssw.fortress.ui;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.eclipse.jface.text.rules.IRule;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.IWordDetector;
import org.eclipse.jface.text.rules.Token;

import at.jku.ssw.fortress.ui.UnicodeDatabase.UnicodeMacro;


/**
 * An implementation of <code>IRule</code> capable of detecting words
 * Word rules also allow for the association of tokens with specific words.
 * That is, not only can the rule be used to provide tokens for exact matches,
 * but also for the generalized notion of a word in the context in which it is used.
 * A word rules uses a word detector to determine what a word is.
 *
 * @see IWordDetector
 */
public class AsciiRule implements IRule {
	
	private static final String[] GREEK = new String[] { "alpha", "beta", "gamma", "delta",
			"epsilon", "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu", "nu", "xi",
			"omicron", "pi", "rho", "sigma", "tau", "upsilon", "phi", "chi", "psi", "omega",
			"ALPHA", "BETA", "GAMMA", "DELTA", "EPSILON", "ZETA", "ETA", "THETA", "IOTA",
			"KAPPA", "LAMBDA", "MU", "NU", "XI", "OMICRON", "PI", "RHO", "SIGMA", "TAU",
			"UPSILON", "PHI", "CHI", "PSI", "OMEGA", };

	/** Internal setting for the un-initialized column constraint */
	protected static final int UNDEFINED= -1;

	/** The word detector used by this rule */
	protected IWordDetector fDetector;
	/** The default token to be returned on success and if nothing else has been specified. */
	protected IToken fDefaultToken;
	protected IToken fAsciiToken;
	/** The column constraint */
	protected int fColumn= UNDEFINED;
	/** The table of predefined words and token for this rule */
	protected Map fWords= new HashMap();
	protected Set fFortress= new HashSet();
	protected Set<String> fStandard= new HashSet<String>();
	protected Set<String> fAlternative= new HashSet<String>();
	protected Set<String> fOmmited= new HashSet<String>();
	/** Buffer used for pattern detection */
	private StringBuffer fBuffer= new StringBuffer();
	private Pattern pattern;

	public AsciiRule(IWordDetector detector, IToken defaultToken, IToken asciiToken) {
		Assert.isNotNull(detector);
		Assert.isNotNull(defaultToken);
		fDetector= detector;
		fDefaultToken= defaultToken;
		fAsciiToken = asciiToken;
		
		MacroManager mm = new MacroManager();
//		mm.loadMacros("ascii.txt", "Abbreviations");
//		for(Macro m : mm.getMacros("Abbreviations")) {
//			fFortress.add(m.name);
//		}
		for(UnicodeMacro m : UnicodeDatabase.INSTANCE.getMacros()) {
			fStandard.add(m.name);
			if(m.name.contains("LETTER_")) {
				fOmmited.add(m.name.replace("LETTER_", ""));
			}
			if(m.name.contains("DIGIT_")) {
				fOmmited.add(m.name.replace("DIGIT_", ""));
			}
			if(m.name.contains("RADICAL_")) {
				fOmmited.add(m.name.replace("RADICAL_", ""));
			}
			if(m.name.contains("NUMERAL_")) {
				fOmmited.add(m.name.replace("NUMERAL_", ""));
			}
		}
		for(UnicodeMacro m : UnicodeDatabase.INSTANCE.getAlternativeMacros()) {
			fAlternative.add(m.name);
			if(m.name.contains("LETTER_")) {
				fOmmited.add(m.name.replace("LETTER_", ""));
			}
			if(m.name.contains("DIGIT_")) {
				fOmmited.add(m.name.replace("DIGIT_", ""));
			}
			if(m.name.contains("RADICAL_")) {
				fOmmited.add(m.name.replace("RADICAL_", ""));
			}
			if(m.name.contains("NUMERAL_")) {
				fOmmited.add(m.name.replace("NUMERAL_", ""));
			}
		}
		
		String regex = "";
		boolean first = true;
		for(String s : GREEK) {
			if(!first) {
				regex += "|\n";
			}
			first = false;
			String macro = "\\A#{s}_.*|.*_#{s}_.*|.*_#{s}\\z";
			String part = macro.replace("#{s}", s);
			regex += part;
		}
		pattern = Pattern.compile(regex);
	}

	/**
	 * Adds a word and the token to be returned if it is detected.
	 *
	 * @param word the word this rule will search for, may not be <code>null</code>
	 * @param token the token to be returned if the word has been found, may not be <code>null</code>
	 */
	public void addWord(String word, IToken token) {
		Assert.isNotNull(word);
		Assert.isNotNull(token);

		fWords.put(word, token);
	}

	/**
	 * Sets a column constraint for this rule. If set, the rule's token
	 * will only be returned if the pattern is detected starting at the
	 * specified column. If the column is smaller then 0, the column
	 * constraint is considered removed.
	 *
	 * @param column the column in which the pattern starts
	 */
	public void setColumnConstraint(int column) {
		if (column < 0)
			column= UNDEFINED;
		fColumn= column;
	}

	/*
	 * @see IRule#evaluate(ICharacterScanner)
	 */
	public IToken evaluate(ICharacterScanner scanner) {
		int c= scanner.read();
		if (fDetector.isWordStart((char) c)) {
			if (fColumn == UNDEFINED || (fColumn == scanner.getColumn() - 1)) {

				fBuffer.setLength(0);
				do {
					fBuffer.append((char) c);
					c= scanner.read();
				} while (c != ICharacterScanner.EOF && fDetector.isWordPart((char) c));
				scanner.unread();

				String name = fBuffer.toString();
				IToken token= (IToken) fWords.get(name);
				if (token != null)
					return token;
				
				if(fFortress.contains(name)) {
					return fAsciiToken;
				}
				if(fStandard.contains(name)) {
					return fAsciiToken;
				}
				if(fAlternative.contains(name)) {
					return fAsciiToken;
				}
				if(fOmmited.contains(name)) {
					return fAsciiToken;
				}
				
		        Matcher m = pattern.matcher(name);
		        if(m.matches()) {
		        	return fAsciiToken;
		        }

				if (fDefaultToken.isUndefined())
					unreadBuffer(scanner);

				return fDefaultToken;
			}
		}

		scanner.unread();
		return Token.UNDEFINED;
	}

	/**
	 * Returns the characters in the buffer to the scanner.
	 *
	 * @param scanner the scanner to be used
	 */
	protected void unreadBuffer(ICharacterScanner scanner) {
		for (int i= fBuffer.length() - 1; i >= 0; i--)
			scanner.unread();
	}
}
